﻿namespace LogManager.Gui.ViewModels.Processing
{
    using LogManager.Core.Models;
    using LogManager.Utils.Helpers;
    using LogManager.Utils.Unity;
    using Microsoft.Practices.Unity;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System;

    public class HierarchicalItemProcessModel
    {
        public ObservableCollection<ItemProcessModel> RootItems { get; private set; }

        public HierarchicalItemProcessModel()
        {
            this.RootItems = new ObservableCollection<ItemProcessModel>();
        }

        public void InitFromConfiguration(IConfiguration config, Func<ItemProcessModel> createItemProcessModel)
        {
            this.RootItems.Clear();

            foreach (var warehouse in config.Warehouses)
            {
                var warehouseProcess = createItemProcessModel();

                warehouseProcess.Name = warehouse.Name;
                warehouseProcess.SecondaryImage = "/images/home.png";
                warehouseProcess.Item = warehouse;

                foreach (var plateform in warehouse.Plateforms)
                {
                    var plateformProcess = createItemProcessModel();
                    plateformProcess.Name = plateform.Name;
                    plateformProcess.SecondaryImage = "/images/plateform.png";
                    plateformProcess.Item = plateform;
                    plateformProcess.Parent = warehouseProcess;

                    foreach (var server in plateform.Servers)
                    {
                        var serverProcess = createItemProcessModel();
                        serverProcess.Name = server.Name;
                        serverProcess.SecondaryImage = "/images/server.png";
                        serverProcess.Item = server;
                        serverProcess.Parent = plateformProcess;

                        foreach (var location in server.Locations)
                        {
                            var locationProcess = createItemProcessModel();
                            locationProcess.Name = location.Name;
                            locationProcess.SecondaryImage = "/images/folder.png";
                            locationProcess.Item = location;
                            locationProcess.Parent = serverProcess;

                            serverProcess.Children.Add(locationProcess);
                        }

                        plateformProcess.Children.Add(serverProcess);
                    }

                    warehouseProcess.Children.Add(plateformProcess);
                }

                this.RootItems.Add(warehouseProcess);
            }
        }

        public ItemProcessModel Find(object searchObj)
        {
            var Alllocations = RootItems.Flatten(p => p.Item == searchObj, p => p.Children);
            return Alllocations.SingleOrDefault();
        }
    }
}
